<template>
  <div>
    <!-- 搜索框 -->
    <search-bar @onSearch="onSearch" />
    <!-- 搜索框 -->
      <div class="btns">
      <!-- 新增菜品 -->
      <el-button @click="addFoodModel" type="success">新增菜品</el-button>
       <!-- 批量导入 -->
      <el-upload action="#" accept=".xlsx, .xls" :before-upload="readExcel">
        <el-button type="success">批量导入</el-button>
      </el-upload>
      <!-- 下载模板 -->
      <el-button @click="exportItemTpl" type="success">下载模板</el-button>
    </div>
    <!-- food列表 -->
    <el-table :data="cates" stripe="false" style="width: 100% ; margin-top :20px; height:500px">
      <el-table-column prop="cateName" label="食品名称" width="200" />
      <el-table-column prop="intro" label="食品介绍" />
      <el-table-column prop="num" label="评分" class="cell" />
      <el-table-column prop="icon" label="图片">
        <template #default="{ row }">
          <div>
            <img :src="row.icon" width="50" alt="">
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="enable" label="是否上架">
        <template #default="{ row }">
          <el-switch v-model="row.enable"  inline-prompt active-text="上架" @change="switchSaleState(row.id, row.enable)"
          inactive-text="下架" />
        </template>
      </el-table-column>
      <el-table-column prop="enable" label="操作">
        <template #default="{ row }">
          <div>
            <!-- 修改菜品 -->
            <el-button type="primary" icon="Edit" @click="updateFoodModel(row.id)"></el-button>
            <!-- 删除菜品 -->
            <el-button type="danger" icon="Delete" @click="deleteFoodModel(row.id)"></el-button>
            <!--  <el-switch v-model="row.enable"
              style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949" /> -->
          </div>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination v-model:page-size="pageSize" v-model:current-page="page" layout="prev, pager, next, jumper, sizes"
      :total="total" />
    <!-- 添加菜品弹窗 -->
    <el-dialog v-model="addFoodShow" title="添加菜品" width="40%">
      <!-- 添加菜品组件 -->
      <add-food :cates="cates" />
    </el-dialog>
    <!-- 修改菜品弹窗 -->
    <el-dialog v-model="updateFoodShow" title="修改菜品" width="40%">
      <update-food :cates="cates" :id="cateId" />
    </el-dialog>
  </div>
</template>

<script>
import { fetchCates, deleteFood, addItems, updateFood } from '@/api/FoodLists'
import SearchBar from '@/components/SearchBar.vue'
import AddFood from './components/AddFood.vue'
import UpdateFood from './components/UpdateFood.vue'
import { read, utils, writeFileXLSX } from 'xlsx'

export default {
  name: 'FoodLists',
  data () {
    return {
      cateId: -1,
      cates: [],
      // 搜索
      searchBar: {
        key: '',
        start: '',
        end: ''
      },
      // 分页
      page: 1,
      pageSize: 5,
      items: [],
      total: 0,
      addFoodShow: false,
      updateFoodShow: false
    }
  },
  methods: {
    deleteFoodModel (id) {
      this.$confirm('确定彻底删除此菜品吗？', '删除').then(() => {
        deleteFood(id).then(res => {
          if (res.data.code === 200) {
            this.$message({
              type: 'success',
              message: res.data.msg
            })
            this.fetchCates()
            // this.$router.go(0)
          }
        })
      })
    },
    addFoodModel () {
      this.addFoodShow = true
    },
    updateFoodModel (id) {
      this.updateFoodShow = true
      this.cateId = id
    },
    onSearch (searchBar) {
      this.searchBar = searchBar
      this.fetchCates()
    },
    // 请求商品列表
    fetchCates () {
      fetchCates({
        ...this.searchBar,
        page: this.page,
        pageSize: this.pageSize
      }).then(res => {
        console.log(res)
        if (res.data.code === 200) {
          this.cates = res.data.data.lists
          this.total = res.data.data.total
        }
      })
    },
    readExcel (file) {
      const fd = new FileReader()
      fd.readAsArrayBuffer(file)
      fd.onload = () => {
        const wb = read(fd.result)
        const data = utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]])
        const _data = data.map(cates => {
          return {
            itemName: cates.商品名,
            price: cates.商品价格,
            desc: cates.商品描述
          }
        })
        // 请求批量添加商品的接口
        addItems({
          items: _data
        }).then(res => {
          if (res.data.code === 200) {
            this.$message({
              type: 'success',
              message: res.data.msg
            })
            this.$router.go(0)
          }
        })
      }
      return false
    },
    exportItemTpl () {
    // 点击导出excel
    // 导出数据
      const data = [
        {
          商品名: '商品1',
          商品价格: 10,
          商品描述: '这是描述'
        }
      ]
      const ws = utils.json_to_sheet(data)
      const wb = utils.book_new()
      utils.book_append_sheet(wb, ws, 'Data')
      writeFileXLSX(wb, '菜品excel模板.xlsx')
    },
    switchSaleState (id, onsale) {
      // 行内修改商品选中状态
      updateFood({
        id,
        onsale
      }).then(res => {
        if (res.data.code === 200) {
          this.$message({
            type: 'success',
            message: res.data.msg,
            duration: 2000,
            onClose: () => {
              this.$router.go(0)
            }
          })
        }
      })
    }

  },
  watch: {
    // 监听当前页 和 一页多少条  重新请求列表
    page () {
      this.fetchCates()
    },
    pageSize () {
      this.fetchCates()
    }
  },
  created () {
    this.fetchCates()
  },
  components: {
    SearchBar,
    AddFood,
    UpdateFood
  }
}
</script>

<style lang="scss" scoped>
:deep .cell {
  text-align: center;
}
.btns{
  width: 280px;
  display: flex;
  justify-content: space-between;
}
</style>
